package com.dev.cmielke.util;

import java.io.File;

import org.apache.log4j.Logger;

public class ExternalZipTool implements ApplicationContants
{
	private static Logger log = Logger.getLogger(ExternalZipTool.class);
	
	public static boolean buildEPubFile(String filename)
	{
		log.debug("> buildEPubFile");
		boolean isBuildOK = false;
		try
		{
			log.debug("Calling external ZIP-application");
			
			log.debug("1. Call: Adding only mimetype");
			log.debug("ProcessBuilder-String [cmd, /c, start, ../extCmd/zip.exe, -Xr9D, ../"+ EPUB_OUTPUT_DIRECTORY + filename +".epub, mimetype]");
			ProcessBuilder builder = new ProcessBuilder( "cmd", "/c", "start", "../extCmd/zip.exe", "-Xr9D", "../"+EPUB_OUTPUT_DIRECTORY + filename + ".epub", "mimetype");
			log.debug("Starting-Directory: [" + OUTPUT_DIRECTORY + "]");
		    builder.directory( new File(OUTPUT_DIRECTORY) ); 
		    Process p = builder.start(); 
		    
		    int returnCode = p.waitFor();
		    if(returnCode == 0)
		    {
		    	log.debug("Process return with ReturnCode ["+ returnCode +"] - OK !");
		    }
		    else
		    {
		    	log.error("Process return with ReturnCode ["+ returnCode +"] - FAILURE !");
		    	log.fatal("Terminating Application!");
		    	System.exit(1);
		    }
		    log.debug("1. Call: complete !");
		    		    
		    waitForProcess();
		    
		    log.debug("2. Call: Adding all other files");		    
			log.debug("ProcessBuilder-String [cmd, /c, start, ../extCmd/zip.exe, -Xr9D, ../"+ EPUB_OUTPUT_DIRECTORY + filename +".epub, *]");
			builder = new ProcessBuilder( "cmd", "/c", "start", "../extCmd/zip.exe", "-Xr9D", "../"+ EPUB_OUTPUT_DIRECTORY + filename + ".epub", "*");
		    builder.directory( new File("generatedFiles") ); 
		    p = builder.start(); 
		    
		    returnCode = p.waitFor();
		    if(returnCode == 0)
		    {
		    	log.debug("Process return with ReturnCode ["+ returnCode +"] - OK !");
		    }
		    else
		    {
		    	log.error("Process return with ReturnCode ["+ returnCode +"] - FAILURE !");
		    	log.fatal("Terminating Application!");
		    	System.exit(1);
		    }
		    log.debug("2. Call: complete !");
		    
		    isBuildOK = true;
		}
		catch (Exception e)
		{
			log.error("Error occured during building Epub-File!", e);
		}
		log.debug("< buildEPubFile");		
		return isBuildOK;
	}
	
	public static void waitForProcess()
	{
		log.debug("> waitForProcessTermination");
		int count = 0;
		for(int i = 0; i < 1000000000; i++){ count++; count--;}
		count = 0;
		for(int i = 0; i < 1000000000; i++){ count++; count--;}
		log.debug("< waitForProcessTermination");
	}
	
	public static void main(String[] args)
	{
		LoggingUtils.configureLog4J();
		ExternalZipTool.buildEPubFile("PerryRhodan_Band474");
	}
}
